import os
import random
import string

from PIL import ImageDraw, Image, ImageFilter, ImageFont


# 定义图片验证码类

class ImageVerify:
    def __init__(self, width=140, height=40, length=4, size=28):
        """

        :param width: 图片宽
        :param height: 图片高
        :param length: 字符个数
        :param size: 字体大小
        """
        self.width = width
        self.height = height
        self.length = length
        self.size = size

    # 生成随机验证码
    def random_str(self):
        # 生成26个字母+数字组合
        sourse = string.ascii_letters + string.digits
        return ''.join(random.choices(sourse,k = self.length))

    # 生成验证码颜色 随机生成颜色  颜色取值范围0-255
    def random_color(self,start=0,end = 255):
        res = [random.randint(start, end) for i in range(3)]
        return tuple(res)


    # 定义干扰线
    def random_lines(self,draw):
        for i in range(self.length):
            lines = [(random.randint(0,self.width),random.randint(0,self.height)) for i in range(2)]
            draw.line(lines, fill=self.random_color(64,255),width=2)

    # 定义干扰点
    def random_points(self,draw,rate):
        for i in range(self.width):
            for j in range(self.height):
                if random.randint(0,100) < rate:
                    draw.point((i,j),fill=self.random_color(64,255))


    # 整合生成图片
    def verify_code(self):
        image = Image.new("RGB",(self.width,self.height),(255,255,255))
        # 创建字体对象  根据字体生成字符串  dirname获取文件夹名
        file = os.path.dirname(os.path.abspath(__file__))  # 得到当前py文件的所在目录的绝对路径 整个代码是找utils文件夹
        # 设置图片路径
        font = ImageFont.truetype(f'{file}/HYYakuHei-85W.ttf', self.size)
        draw = ImageDraw.Draw(image)
        # 画干扰线
        self.random_lines(draw)
        # 画干扰点
        self.random_points(draw,10)
        # 获取验证码
        code = self.random_str()
        # 设置验证码排序
        for i in range(self.length):
            draw.text((35*i,0),code[i],font=font,fill = self.random_color(64,255))
        img = image.filter(ImageFilter.BLUR)
        return img,code
if __name__ == '__main__':
    imageVerify = ImageVerify()

    img,code = imageVerify.verify_code()
    with open("test.png","wb") as f:
        img.save(f)
    print(code)